package com.cn.xt.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cn.xt.utils.CustomUserUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis自动填充规则类
 * @author liuyu on 2021/1/18.
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private CustomUserUtil customUserUtil;
    @Override
    public void insertFill(MetaObject metaObject) {
        //创建时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        //是否删除
        this.strictInsertFill(metaObject, "isDelete", Integer.class, 0);
        //版本号
        this.strictInsertFill(metaObject, "version", Integer.class, 1);
        //创建人
        String userId = customUserUtil.getUserId();
        if(userId!=null) {
            this.strictInsertFill(metaObject, "creater", String.class, userId);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        //更新人
        String userId = customUserUtil.getUserId();
        if(userId!=null) {
            this.strictInsertFill(metaObject, "updater", String.class, userId);
        }
    }
}
